const jwt = require('jsonwebtoken');
const User = require('../models/User');

const protect = async (req, res, next) => {
  let token;

  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith('Bearer')
  ) {
    try {
      token = req.headers.authorization.split(' ')[1];
      
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      
      req.user = await User.findById(decoded.id).select('-password');
      
      // 检查token是否即将过期（少于5分钟），如果是则生成新token
      const now = Date.now() / 1000;
      if (decoded.exp - now < 300) {
        const newToken = jwt.sign(
          { id: decoded.id },
          process.env.JWT_SECRET,
          { expiresIn: process.env.JWT_EXPIRES_IN }
        );
        res.set('x-new-token', newToken);
      }
      
      next();
    } catch (error) {
      console.error(error);
      res.status(200).json({ errCode: 401, errMsg: '未授权访问，请重新登录' });
    }
  }

  if (!token) {
    res.status(200).json({ errCode: 401, errMsg: '未提供token，授权被拒绝' });
  }
};

module.exports = { protect };